package controller;

import dao.MemberUserDao;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.MemberUser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Objects;

@WebServlet(name = "UserServlet", value = "/User")
public class UserServlet extends HttpServlet {
    public static final Logger logger = LogManager.getLogger(UserServlet.class);

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String method = request.getParameter("method") == null ? "" : request.getParameter("method");
        MemberUserDao memberUserDao = new MemberUserDao();

        // 登录
        if ("login".equals(method)) {
            // 获取会话验证码
            String codeValidate;
            if (request.getSession().getAttribute("codeValidate") != null) {
                codeValidate = (String) request.getSession().getAttribute("codeValidate");
            } else {
                codeValidate = "Error";
            }
            // 获取用户提交验证码
            String validateCode = request.getParameter("validateCode");
            // 验证码转小写并比较是否相等
            logger.info("Session.validateCode:" + codeValidate + " getParameter.validateCode:" + validateCode);
            assert codeValidate != null;
            if (!Objects.equals(codeValidate.toLowerCase(), validateCode.toLowerCase())) {
                logger.info("User login validateCode Error");
                request.getSession().setAttribute("login_error", "验证码错误");
                response.sendRedirect("/member/login.jsp");
            } else {
                try {
                    MemberUser memberUser = (MemberUser) request.getAttribute("login");
                    if (memberUserDao.Login(memberUser)) {
                        request.getSession().setAttribute("username", memberUser.getUsername());
                        int userId = memberUserDao.getUserId(memberUser);
                        logger.info("Now login userID = " + userId);
                        request.getSession().setAttribute("user_id", userId);
                        response.sendRedirect("/index.jsp");
                    } else {
                        request.getSession().setAttribute("login_error", "请检查用户名和密码是否正确");
                        response.sendRedirect("/member/login.jsp");
                    }
                } catch (SQLException e) {
                    logger.error(e);
                    throw new RuntimeException(e);
                }
            }
        }

        // 注销登录 其实无非就是删除会话的过程
        if ("logout".equals(method)) {
            if (request.getSession().getAttribute("username") != null) {
                logger.info("Now username:" + request.getSession().getAttribute("username") + " logout!");
                request.getSession().removeAttribute("username");
                request.getSession().removeAttribute("user_id");
            }
            response.sendRedirect("/member/login.jsp");
        }

        // 注册
        if ("regUser".equals(method)) {            // 获取会话验证码
            String codeValidate;
            if (request.getSession().getAttribute("codeValidate") != null) {
                codeValidate = (String) request.getSession().getAttribute("codeValidate");
            } else {
                codeValidate = "Error";
            }
            // 获取用户提交验证码
            String validateCode = request.getParameter("validateCode");
            // 验证码转小写并比较是否相等
            logger.info("Session.validateCode:" + codeValidate + " getParameter.validateCode:" + validateCode);
            assert codeValidate != null;
            if (!Objects.equals(codeValidate.toLowerCase(), validateCode.toLowerCase())) {
                logger.info("User register validateCode Error");
                request.getSession().setAttribute("user_reg_message", "验证码错误");
                response.sendRedirect("/member/register.jsp");
            } else {
                try {
                    MemberUser memberUser = (MemberUser) request.getAttribute("regUser");
                    if (!Objects.equals(memberUser.getPassword(), memberUser.getConfirmPassword())) {
                        request.getSession().setAttribute("user_reg_message", "密码与确认密码不一致");
                        response.sendRedirect("/member/register.jsp");
                    } else if (memberUserDao.regUser(memberUser)) {
                        request.getSession().setAttribute("user_reg_message", "注册成功");
                        response.sendRedirect("/member/login.jsp");
                    } else {
                        request.getSession().setAttribute("user_reg_message", "注册失败");
                        response.sendRedirect("/member/register.jsp");
                    }
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        // 修改密码
        if ("chPass".equals(method)) {
            // 获取会话验证码
            String codeValidate;
            if (request.getSession().getAttribute("codeValidate") != null) {
                codeValidate = (String) request.getSession().getAttribute("codeValidate");
            } else {
                codeValidate = "Error";
            }
            // 获取用户提交验证码
            String validateCode = request.getParameter("validateCode");
            // 验证码转小写并比较是否相等
            logger.info("Session.validateCode:" + codeValidate + " getParameter.validateCode:" + validateCode);
            assert codeValidate != null;
            if (!Objects.equals(codeValidate.toLowerCase(), validateCode.toLowerCase())) {
                logger.info("User change password validateCode Error");
                request.getSession().setAttribute("user_chPass_message", "验证码错误");
                response.sendRedirect("/member/password.jsp");
            } else {
                try {
                    MemberUser memberUser = (MemberUser) request.getAttribute("chPass");
                    memberUser.setId((Integer) request.getSession().getAttribute("user_id"));
                    logger.info("session user id:" + memberUser.getId());
                    if (memberUserDao.userChangePassword(memberUser)) {
                        request.getSession().setAttribute("user_chPass_message", "密码修改成功");
                    } else {
                        request.getSession().setAttribute("user_chPass_message", "密码修改失败");
                    }
                    response.sendRedirect("/member/password.jsp");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
